package com.aaa.unilt;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: TODO
 * @date 2022/11/23
 */
public class JwtUntil {
    //签名
    private static final String SIGN="aaa";
    //1.通过JWT生成token字符串
    public static String createToken(Map<String,Object> params){
        Map<String,Object> head=new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ","JWT");

        //定义颁发时间
        Date iss = new Date();
        //过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,1);
        Date time = instance.getTime();


        String sign = JWT.create()
                //指定头部信息
                .withHeader(head)
                //载荷的过期时间
                .withExpiresAt(time)
                //颁发时间
                .withIssuedAt(iss)
                //颁发人
                .withIssuer("chenQing")
                //自定义的载荷内容
//                .withClaim("name", "成龙")
//                .withClaim("age", 70)
                .withClaim("userInfo",params)
                //签名
                .sign(Algorithm.HMAC256(SIGN));
        return sign;
    }
    //2.判断token是否合法
    public static boolean verifyToken(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
        try {
            DecodedJWT verify = build.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("token令牌无效");
            return false;
        }
    }

    //3.解析内容
    public static Map<String,Object> over(String token){
        Map<String,Object> user=JWT.decode(token).getClaim("userInfo").asMap();
        return user;
    }

    public static void main(String[] args) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name","张三丰");
        hashMap.put("age",19);
        String token=createToken(hashMap);
        System.out.println(token);
        Map<String, Object> map=over(token);
        System.out.println(map);



        boolean b = verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySW5mbyI6eyJuYW1lIjoi5byg5LiJ5LiwIiwiYWdlIjoxOX0sImlzcyI6ImNoZW5RaW5nIiwiZXhwIjoxNjY5MTk1ODAyLCJpYXQiOjE2NjkxOTQwMDJ9.BTCAFXN5xV3UzoKautP9ToRL9_cw_vhGSsfs3pmsTbw ");
        System.out.println(b);
    }
}
